package com.exam.controller;

import com.exam.entity.Answer;
import com.exam.entity.ApiResult;
import com.exam.entity.Questionnaire;
import com.exam.serviceimpl.AnswerServiceImpl;
import com.exam.serviceimpl.QuestionnaireServiceImpl;
import com.exam.util.ApiResultHandler;
import com.exam.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
public class AnswerController {

    @Autowired
    private AnswerServiceImpl answerService;

    @Autowired
    private QuestionnaireServiceImpl questionnaireService;
    @PostMapping("/addAnswer")
    public ApiResult addAnswer(@RequestBody Answer answer){
        String id = UUIDUtil.getOneUUID();
        answer.setId(id);
        answer.setIsVaild(1);

        if(answer.getGroupId() == null){
            answer.setGroupId("0");
        }
        Questionnaire questionnaire = questionnaireService.findQuestionnaireById(answer.getQuestionnaireId());
        if(questionnaire == null ){
            return ApiResultHandler.buildApiResult(400, "预览界面，无法提交", null);
        }else if(questionnaire.getAnswerTotal() <= 0){
            return ApiResultHandler.buildApiResult(400, "问卷已达到提交上限", null);
        }
        List<Answer> test = answerService.findAnswerByBelongQu(answer);
        if(!test.isEmpty()){
            return ApiResultHandler.buildApiResult(400, "请勿重复提交答卷", null);
        }
        questionnaire.setAnswerTotal(questionnaire.getAnswerTotal()-1);
        questionnaireService.reduceNum(questionnaire);
        int num = answerService.addAnswerByForm(answer);
        if(num == 0){
            return ApiResultHandler.buildApiResult(400, "提交失败", null);
        }else{


            return ApiResultHandler.buildApiResult(200, "查询成功", null);
        }

    }
}
